﻿Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Web


Public NotInheritable Class WebUtil

    Public Shared Function DoPost(ByVal url As String, ByVal parameters As IDictionary(Of String, String)) As String

        Dim req As HttpWebRequest = GetWebRequest(url, "POST")
        req.ContentType = "application/x-www-form-urlencoded;charset=utf-8"

        Dim postData As Byte() = Encoding.UTF8.GetBytes(BuildQuery(parameters))
        Dim reqStream As Stream = req.GetRequestStream()
        reqStream.Write(postData, 0, postData.Length)
        reqStream.Close()

        Dim rsp As HttpWebResponse = DirectCast(req.GetResponse(), HttpWebResponse)
        Dim _encoding As Encoding = Encoding.GetEncoding(rsp.CharacterSet)
        Return GetResponseAsString(rsp, _encoding)

    End Function

    Private Shared Function GetWebRequest(ByVal url As String, ByVal p2 As String) As HttpWebRequest
        Throw New NotImplementedException
    End Function

    Private Shared Function GetResponseAsString(ByVal rsp As HttpWebResponse, ByVal encoding__1 As Encoding) As String
        Throw New NotImplementedException
    End Function






















    ''' <summary>
    ''' 组装GET请求URL。
    ''' </summary>
    ''' <param name="url">请求地址</param>
    ''' <param name="parameters">请求参数</param>
    ''' <returns>带参数的GET请求URL</returns>
    Public Shared Function BuildGetUrl(ByVal url As String, ByVal parameters As IDictionary(Of String, String)) As String
        If parameters IsNot Nothing AndAlso parameters.Count > 0 Then
            If url.Contains("?") Then
                url = url & "&" & BuildQuery(parameters)
            Else
                url = url & "?" & BuildQuery(parameters)
            End If
        End If
        Return url
    End Function

    ''' <summary>
    ''' 组装普通文本请求参数。
    ''' </summary>
    ''' <param name="parameters">Key-Value形式请求参数字典</param>
    ''' <returns>URL编码后的请求数据</returns>
    Public Shared Function BuildQuery(ByVal parameters As IDictionary(Of String, String)) As String
        Dim postData As New StringBuilder()
        Dim hasParam As Boolean = False

        Dim dem As IEnumerator(Of KeyValuePair(Of String, String)) = parameters.GetEnumerator()
        While dem.MoveNext()
            Dim name As String = dem.Current.Key
            Dim value As String = dem.Current.Value
            ' 忽略参数名或参数值为空的参数
            If Not String.IsNullOrEmpty(name) AndAlso Not String.IsNullOrEmpty(value) Then
                If hasParam Then
                    postData.Append("&")
                End If

                postData.Append(name)
                postData.Append("=")
                postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8))
                hasParam = True
            End If
        End While

        Return postData.ToString()
    End Function

End Class
